<?php

/**
 * This is the model class for table "menuadmin".
 *
 * The followings are the available columns in table 'menuadmin':
 * @property string $MenuAdminID
 * @property string $MenuName
 * @property string $MenuPath
 * @property string $MenuIcon
 * @property string $MenuImage
 * @property integer $IsActive
 * @property integer $IsHome
 * @property string $MenuCode
 * @property integer $Menu1
 * @property integer $Menu2
 * @property integer $Menu3
 * @property integer $Menu4
 * @property integer $MenuParentID
 */
class Menuadmin extends CActiveRecord
{
	/**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'menuadmin';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('MenuCode, MenuName', 'required'),
            array('IsActive, IsHome, Menu1, Menu2, Menu3, Menu4, MenuParentID', 'numerical', 'integerOnly'=>true),
            array('MenuName', 'length', 'max'=>50),
            array('MenuPath, MenuIcon, MenuImage', 'length', 'max'=>200),
            array('MenuCode', 'length', 'max'=>100),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('MenuAdminID, MenuName, MenuPath, MenuIcon, MenuImage, IsActive, IsHome, MenuCode, Menu1, Menu2, Menu3, Menu4, MenuParentID', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }
    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('MenuAdminID',$this->MenuAdminID,true);
        $criteria->compare('MenuName',$this->MenuName,true);
        $criteria->compare('MenuPath',$this->MenuPath,true);
        $criteria->compare('MenuIcon',$this->MenuIcon,true);
        $criteria->compare('MenuImage',$this->MenuImage,true);
        $criteria->compare('IsActive',$this->IsActive);
        $criteria->compare('IsHome',$this->IsHome);
        $criteria->compare('MenuCode',$this->MenuCode,true);
        $criteria->compare('Menu1',$this->Menu1);
        $criteria->compare('Menu2',$this->Menu2);
        $criteria->compare('Menu3',$this->Menu3);
        $criteria->compare('Menu4',$this->Menu4);
        $criteria->compare('MenuParentID',$this->MenuParentID);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Menuadmin the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
	public function attributeLabels()
	{
		return array(
			'MenuAdminID' => 'Menu Admin',
			'MenuName' => 'Tên menu',
			'MenuPath' => 'Đường dẫn',
			'MenuIcon' => 'Icon',
			'MenuImage' => 'Ảnh đại diện',
			'IsActive' => 'Kích hoạt',
			'IsHome' => 'Trang chủ',
			'MenuCode' => 'Mã menu',
         'MenuParentID' => 'Menu cha',
			'Menu1' => 'Menu cấp 1',
			'Menu2' => 'Menu cấp 2',
			'Menu3' => 'Menu cấp 3',
			'Menu4' => 'Menu cấp 4',
		);
	}
   
   /**
    * Get all category
   */
   public function getAll(){
      $return = array();
      $object = $this->findAll();
      if(count($object) > 0){
         foreach($object as $item){
            $return[$item['MenuAdminID']] = $item->attributes;
         }
      }
      return $return;
   }
   
   /**
    * Lay danh sach cat dang cay. Su dung de quy
   */
   public function getTree($all_cate, $parent_id = 0, $trees = array(0 => 'Không chọn'),$delimiter = ''){
      if(!$trees) 
      {
      $trees = array();
      }
      foreach($all_cate as $key=>$value){
         if($value['MenuParentID'] == $parent_id){
            $trees[$value['MenuAdminID']] = $delimiter.$value['MenuName'];
            $trees = $this->getTree($all_cate,$value['MenuAdminID'],$trees,$delimiter.'---');
         }
            
      }
      return $trees;
   }
   
   /**
    * Return all menu. If level != 0 return by level
    * @param int $level
    * @return array
    * 
   */
   public function getMenuByLevel($level = 0){
      $returns = array();
      $sql = " SELECT * FROM " . $this->tableName() . " WHERE 1";
      $where = '';
      if($level > 0 && $level < 4){
         switch ($level){
            case 1 :
               $where .= " AND Menu2 = 0";
               break;
            case 2 :
               $where .= " AND Menu3 = 0";
               break;
            case 3 :
               $where .= " AND Menu4 = 0";
         }
      }
      $sql .= $where;
      $object = $this->findAllBySql($sql);
      foreach($object as $item){
         $returns[] = $item->attributes;
      }
      return $returns;
   }
   
   
   /**
    * Get level menu
    * @param int $id
    * @return int level
   */
   public function getLevel($id){    
      //CVarDumper::dump($this->findByPk($id)->attributes,10,true);die();
      $sql = "SELECT * FROM menuadmin WHERE MenuAdminID =:id";
      $db = Yii::app()->db;
      $cmd = $db->createCommand($sql);
      $cmd->bindParam(":id",$id);
      $row = $cmd->queryRow();
      $this->attributes = $row;
      //CVarDumper::dump($row,10,true);die();
      //var_dump($row);die();
      if($this->Menu4 != 0)
         $level = 4;
      else if($this->Menu3 != 0)
         $level = 3;
      else if($this->Menu2 != 0)
         $level = 2;
      else 
         $level = 1;
      return $level;
   }
   
   /**
    * Get parent menu
    * @param int $id
    * @param array menu
   */
   public function getParent($id){
      $returns = array();
      $level = $this->getLevel($id);
      $sql = "SELECT
            	a.*
            FROM
            	menuadmin a
            INNER JOIN (
            	SELECT
            		MenuAdminID,
            		Menu1,
            		Menu2,
            		Menu3,
            		Menu4
            	FROM
            		menuadmin c
            	WHERE
            		MenuAdminID = $id";
      $on_table = '';
      if($level == 2){ // Nếu là menu cấp 2 thì lấy ra mảng menu cha cấp 1
         $on_table_1 = '( b.Menu1 = a.Menu1 
                        AND b.Menu1 > 0 
                        AND a.Menu2 = 0 )';
         $sql_1 = ' ) b ON ' . $on_table . $on_table_1 . ' WHERE a.IsActive = 1';
         $parent_level_1 = $this->findBySql($sql.$sql_1);
         $returns[1] = $parent_level_1->attributes;
         return $returns;
      }
      if($level == 3){ // Nếu là menu cấp 3 thì lấy ra mảng menu cha cấp 2 và cấp 1
         $on_table_1 = '( b.Menu1 = a.Menu1 
                        AND b.Menu1 > 0 
                        AND a.Menu2 = 0 )';
         $sql_1 = ' ) b ON ' . $on_table . $on_table_1 . ' WHERE a.IsActive = 1';
         $parent_level_1 = $this->findBySql($sql.$sql_1);
         $returns[1] = $parent_level_1->attributes;
         $on_table_2 = '( b.Menu1 = a.Menu1 
                        AND b.Menu2 = a.Menu2
                     	AND b.Menu1 > 0
                     	AND a.Menu2 > 0
                     	AND a.menu3 = 0 )';
         $sql_2 = ' ) b ON ' . $on_table . $on_table_2 . ' WHERE a.IsActive = 1';
         $parent_level_2 = $this->findBySql($sql.$sql_2);
         $returns[2] = $parent_level_2->attributes;
      }
      return $returns;
      
   }
   
   /**
    * Get id parent max
    * @param int $id
    * @return int parent id
   */
   public function getIdParentMax($id){
      $returns = 0;
      $sql = "SELECT
               	a.*
               FROM
               	menuadmin a
               INNER JOIN (
               	SELECT
               		MenuAdminID,
               		Menu1,
               		Menu2,
               		Menu3,
               		Menu4
               	FROM
               		menuadmin c
               	WHERE
               		MenuAdminID = $id
               ) b ON (
               	b.Menu1 = a.Menu1
               	AND a.Menu2 = 0
               )
               WHERE
               	a.IsActive = 1
              ";
      $row = $this->findBySql($sql);
      if(!is_null($row))
         $returns = $row->attributes['MenuAdminID'];
      return $returns;
   }
   
   /**
    * Get all child
    * @param int $id
    * @return array child
   */
   public function getChild($id){
      $returns = array();
      //$id = intval($id);
      $level = $this->getLevel($id);
         $sql = "SELECT
                  	a.*
                  FROM
                  	menuadmin a
                  INNER JOIN (
                  	SELECT
                  		MenuAdminID,
                  		Menu1,
                  		Menu2,
                  		Menu3,
                  		Menu4
                  	FROM
                  		menuadmin c
                  	WHERE
                  		MenuAdminID = $id
                  ) b ON ( ";
      if($level == 1){
         //Lấy menu cấp 2
         $sql_2 = "b.Menu1 = a.Menu1
	                 AND a.Menu3 = 0 )
                  WHERE
                  	a.IsActive = 1
                  AND	a.MenuAdminID != $id";
         $childs = $this->findAllBySql($sql.$sql_2);
         $temp = array();
         foreach($childs as $item){
            $temp[] = $item->attributes;
         }
         $returns[2] = $temp;
         
         //Lấy menu cấp 3
         $sql_3 = "b.Menu1 = a.Menu1
	                 AND a.Menu3 > 0 )
                  WHERE
                  	a.IsActive = 1
                  AND	a.MenuAdminID != $id";
         $childs = $this->findAllBySql($sql.$sql_3);
         $temp = array();
         foreach($childs as $item){
            $temp[] = $item->attributes;
         }
         $returns[3] = $temp;
      }else if($level == 2){
         //Lấy menu cấp 3
         $sql_3 = "b.Menu1 = a.Menu1
	                 AND a.Menu3 > 0 )
                  WHERE
                  	a.IsActive = 1
                  AND	a.MenuAdminID != $id";
         $childs = $this->findAllBySql($sql.$sql_3);
         $temp = array();
         foreach($childs as $item){
            $temp[] = $item->attributes;
         }
         $returns[3] = $temp;
      }
      
      return $returns;
      
   }
   
   /**
    * Get all menu level 1
   */
   public function getAllLevel1(){
      $sql = "SELECT * FROM menuadmin WHERE IsActive = 1 AND Menu2 = 0";
      $list = array();
      $object = $this->findAllBySql($sql);
      if(count($object) > 0){
         foreach($object as $item){
            $list[] = $item->attributes;
         }
      }
      return $list;
   }
}
